package biz.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.naming.NamingException;

import biz.AreaBiz;
import dao.AreaDao;
import dao.BaseDao;
import dao.impl.AreaDaoImpl;
import entity.Area;

public class AreaBizImpl implements AreaBiz {

	private AreaDao dao;

	@Override
	public List<Area> findAllArea() {
		Connection conn = null;
		try {
			conn = BaseDao.getConnection();
			this.dao = new AreaDaoImpl(conn);
			List<Area> list = dao.findAll();
			return list;

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public boolean deteleProvince(int id) {
		Connection con = null;
		try {
			con = BaseDao.getConnection();
			con.setAutoCommit(false);

			dao = new AreaDaoImpl(con);
			dao.deleteArea(id);
			List<Area> cities = dao.findCityByPId(id);
			for (Area area : cities) {
				dao.deleteArea(area.getId());
			}

			con.commit();
			return true;
		} catch (SQLException | NamingException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();

		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return false;
	}

	@Override
	public List<Area> findListByPage(int index, int pageSize) {
		AreaDao dao = null;
		List<Area> areas = null;
		Connection con = null;
		try {
			con = BaseDao.getConnection();
			dao = new AreaDaoImpl(con);
			areas = dao.findByPage((index - 1) * pageSize, pageSize);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}finally {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		return areas;

	}

}
